package cn.tsyz.local.shared.security;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.Set;

@Component
public class CorsInterceptor implements HandlerInterceptor {

    // 定义安全域名后缀
    private static final Set<String> SAFE_DOMAINS = new HashSet<String>() {{
        add("localhost");
        add("127.0.0.1");
        add("localhost.com");
        add("localhost.cn");
    }};
    // 可以通过配置文件设置允许的域名
    @Value("${cors.allowed.origins:*}")
    private String allowedOrigins;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String origin = request.getHeader("Origin");

        // 安全检查（可选）
        if (origin != null && !isAllowedOrigin(origin)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }

        // 设置跨域响应头
        if (origin != null) {
            response.setHeader("Access-Control-Allow-Origin", origin);
        } else {
            response.setHeader("Access-Control-Allow-Origin",
                    "*".equals(allowedOrigins) ? "*" : allowedOrigins.split(",")[0]);
        }

        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With, X-XSRF-TOKEN, Accept, Origin, Range");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Expose-Headers", "X-Total-Count, X-Pagination, Content-Disposition");

        // 处理预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return false;
        }

        return true;
    }

    /**
     * 检查是否为允许的域名
     */
    private boolean isAllowedOrigin(String origin) {
        // 如果允许所有域名，直接返回true
        if ("*".equals(allowedOrigins)) {
            return true;
        }

        // 检查是否在安全域名列表中
        for (String safeDomain : SAFE_DOMAINS) {
            if (origin.contains(safeDomain)) {
                return true;
            }
        }

        // 检查是否在配置的允许域名中
        String[] allowedOriginArray = allowedOrigins.split(",");
        for (String allowedOrigin : allowedOriginArray) {
            if (origin.equals(allowedOrigin.trim())) {
                return true;
            }
        }

        return false;
    }
}
